import 'dart:io';
import 'dart:ui' as ui;
import 'dart:ui';
import 'package:get/get.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart';
import 'package:signage/app/data/models/si_font.dart';
import 'package:signage/app/utils/http_client.dart';
import 'package:dio/dio.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/edit_dialog.dart';

class FontManagerController extends GetxController {
  final defaultFontFamily = 'AlibabaPuHuiTi'.obs;
  final httpClient = HttpClient();
  // 内置字体列表
  final builtInFonts = <SIFont>[
    SIFont(
        name: 'AlibabaPuHuiTi',
        variants: {
          SIFontWeight.light: 'AlibabaPuHuiTi-3-Regular.ttf',
        },
        isBuiltIn: true),
  ].obs;
  // 已安装的字体列表
  final installedFonts = <SIFont>[].obs;
  // 动态加载的字体列表
  final localFonts = <SIFont>[].obs;

  // 字体文件存储目录
  late final Directory fontDirectory;

  // 添加选择模式标志
  final isSelectMode = false.obs;
  // 选中的字体
  final selectedFont = Rxn<SIFont>();

  // 存储下载进度
  final downloadProgress = <String, double>{}.obs;

  // 存储正在下载的任务，用于取消下载
  final _downloadTasks = <String, CancelToken>{};

  @override
  void onInit() async {
    super.onInit();
    // 检查是否为选择模式
    if (Get.arguments != null && Get.arguments['selectMode'] == true) {
      isSelectMode.value = true;
    }

    // 初始化字体存储目录
    final appDir = await getApplicationDocumentsDirectory();
    fontDirectory = Directory('${appDir.path}/fonts');
    if (!await fontDirectory.exists()) {
      await fontDirectory.create(recursive: true);
    }

    // 加载已保存的字体
    await loadSavedFonts();

    // 加载网络字体
    await loadNetworkFonts();
  }

  final networkFonts = <SIFont>[].obs;

  // 加载网络字体
  Future<void> loadNetworkFonts() async {
    FontListResponse response = await httpClient.getFontList();
    if (response.code == 200) {
      response.data.forEach((font) {
        // 检查字体是否已经在本地安装
        bool isInstalled = installedFonts
            .any((installedFont) => installedFont.name == font.fontName);

        // 只添加未安装的字体到网络字体列表
        if (!isInstalled) {
          networkFonts.add(SIFont(
            name: font.fontName,
            isBuiltIn: false,
            path: font.url,
          ));
        }
      });
    }
  }

  // 加载已保存的字体
  Future<void> loadSavedFonts() async {
    try {
      final files = await fontDirectory.list().toList();

      for (var file in files) {
        final fontName = File(file.path).uri.pathSegments.last;
        if (!localFonts.contains(fontName)) {
          await _loadFontFromFile(File(file.path));
          final font =
              SIFont(name: fontName, isBuiltIn: false, path: file.path);
          localFonts.add(font);
          installedFonts.add(font);
        }
      }
    } catch (e) {
      print('加载保存的字体失败: $e');
    }
  }

  Future<void> importFonts() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['ttf', 'otf'],
        allowMultiple: true,
      );

      if (result != null) {
        for (var file in result.files) {
          if (file.path != null) {
            final fontFile = File(file.path!);
            final fontName = fontFile.uri.pathSegments.last;

            if (!localFonts.contains(fontName) &&
                !installedFonts.contains(fontName)) {
              final savedFile =
                  await fontFile.copy('${fontDirectory.path}/$fontName');
              await _loadFontFromFile(savedFile);

              final font = SIFont(
                  name: fontName, isBuiltIn: false, path: savedFile.path);
              localFonts.add(font);
              installedFonts.add(font);

              Get.snackbar('', 
                AppLocalizations.of(Get.context!)!.translate('font_imported').replaceFirst('{name}', fontName),
                snackPosition: SnackPosition.BOTTOM);
            } else {
              Get.snackbar('', 
                AppLocalizations.of(Get.context!)!.translate('font_already_exists').replaceFirst('{name}', fontName),
                snackPosition: SnackPosition.BOTTOM);
            }
          }
        }
      }
    } catch (e) {
      Get.snackbar('', 
        AppLocalizations.of(Get.context!)!.translate('font_import_failed').replaceFirst('{error}', e.toString()),
        snackPosition: SnackPosition.BOTTOM);
    }
  }

  // 动态加载字体文件
  Future<void> _loadFontFromFile(File fontFile) async {
    try {
      final fontLoader = FontLoader(fontFile.uri.pathSegments.last);
      final bytes = await fontFile.readAsBytes();
      fontLoader.addFont(Future.value(bytes.buffer.asByteData()));
      await fontLoader.load();
    } catch (e) {
      print('加载字体失败: $e');
      rethrow;
    }
  }

  Future<void> removeFont(String fontName) async {
    if (isBuiltInFont(fontName)) {
      Get.snackbar('',
        AppLocalizations.of(Get.context!)!.translate('built_in_font_delete_error'),
        snackPosition: SnackPosition.BOTTOM,
      );
      return;
    }

    try {
      Get.dialog(TipsDialog(
          title: AppLocalizations.of(Get.context!)!.translate('tip'),
          text: AppLocalizations.of(Get.context!)!.translate('confirm_delete_font'),
          cancelText: AppLocalizations.of(Get.context!)!.translate('cancel'),
          showCancel: true,
          onCancel: () {
            Get.back();
          },
          onConfirm: () async {
            Get.back();
            final file = File('${fontDirectory.path}/$fontName');
            if (await file.exists()) {
              await file.delete();
            }

            localFonts.removeWhere((font) => font.name == fontName);
            installedFonts.removeWhere((font) => font.name == fontName);

            Get.snackbar('',
              AppLocalizations.of(Get.context!)!.translate('font_deleted'),
              snackPosition: SnackPosition.BOTTOM,
            );

            await loadNetworkFonts();
          }));
    } catch (e) {
      Get.snackbar('',
        AppLocalizations.of(Get.context!)!.translate('font_delete_failed'),
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }

  // 判断是否为内置字体
  bool isBuiltInFont(String fontName) {
    return builtInFonts.contains(fontName);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    // 清理所有未完成的下载
    for (final task in _downloadTasks.values) {
      if (!task.isCancelled) {
        task.cancel('Controller disposed');
      }
    }
    super.onClose();
  }

  // 获取所有可用字体列表（包括内置和已安装的所有字重）
  List<SIFont> getAllFonts() {
    List<SIFont> allFonts = [];

    // 展开内置字体的所有字重
    for (var font in builtInFonts) {
      if (font.variants != null) {
        for (var entry in font.variants!.entries) {
          allFonts.add(SIFont(
            name: '${font.name}',
            isBuiltIn: true,
            path: entry.value,
          ));
        }
      }
    }

    // 添加已安装字体
    allFonts.addAll(installedFonts);

    return allFonts;
  }

  // 添加字体选择方法
  void selectFont(SIFont font) {
    if (isSelectMode.value) {
      selectedFont.value = font;
      Get.back(result: font);
    }
  }

  Future<void> downloadFont(String fontName) async {
    try {
      if (downloadProgress.containsKey(fontName)) return;

      final cancelToken = CancelToken();
      _downloadTasks[fontName] = cancelToken;
      downloadProgress[fontName] = 0.0;

      final downloadUrl = await _getFontDownloadUrl(fontName);
      final tempDir = await getTemporaryDirectory();
      final savePath = '${tempDir.path}/$fontName';

      await Dio().download(
        downloadUrl,
        savePath,
        cancelToken: cancelToken,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            downloadProgress[fontName] = received / total;
          }
        },
      );

      final finalPath = '${fontDirectory.path}/$fontName';
      await fontDirectory.create(recursive: true);
      final savedFile = await File(savePath).copy(finalPath);
      await File(savePath).delete();

      await _loadFontFromFile(savedFile);

      final font = SIFont(
        name: fontName,
        path: finalPath,
      );
      installedFonts.add(font);

      downloadProgress.remove(fontName);
      _downloadTasks.remove(fontName);
      networkFonts.removeWhere((font) => font.name == fontName);

      Get.snackbar('',
        AppLocalizations.of(Get.context!)!.translate('download_success').replaceFirst('{name}', fontName),
        snackPosition: SnackPosition.TOP,
      );

    } catch (e) {
      downloadProgress.remove(fontName);
      _downloadTasks.remove(fontName);
      Get.snackbar('',
        AppLocalizations.of(Get.context!)!.translate('download_failed').replaceFirst('{error}', e.toString()),
        snackPosition: SnackPosition.TOP,
      );
    }
  }

  // 取消下载
  void cancelDownload(String fontName) {
    final cancelToken = _downloadTasks[fontName];
    if (cancelToken != null && !cancelToken.isCancelled) {
      cancelToken.cancel('用户取消下载');
      downloadProgress.remove(fontName);
      _downloadTasks.remove(fontName);
    }
  }

  // 获取字体下载链接（需要根据实际API实现）
  Future<String> _getFontDownloadUrl(String fontName) async {
    // TODO: 实现获取下载链接的逻辑

    return networkFonts.firstWhere((font) => font.name == fontName).path!;
  }
}
